﻿using Cxuu.Common;
using Cxuu.Models;
using Cxuu.Service;
using Cxuu.Web.Authorize;
using Google.Protobuf.Collections;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using PetaPoco;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Threading.Tasks;

namespace Cxuu.Web.Admin
{
    [Area("Admin")]
    [Authorize]
    public class UserController : Base
    {
        private readonly LoginUtil _LoginUtil;
        private readonly AdminUserService _adminUserService;
        private readonly AdminUserGroupService _adminUserGroupService;
        private readonly AdminUserDeptService _adminUserDeptService;
        private readonly AdminUserPostService _adminUserPostService;
        private readonly LogService _logService;
        public UserController(
            LoginUtil LoginUtil,
            AdminUserService adminUserService,
            AdminUserGroupService adminUserGroupService,
            LogService logService,
            AdminUserDeptService adminUserDeptService,
            AdminUserPostService adminUserPostService
            )
        {
            _LoginUtil = LoginUtil;
            _adminUserService = adminUserService;
            _adminUserGroupService = adminUserGroupService;
            _logService = logService;
            _adminUserDeptService = adminUserDeptService;
            _adminUserPostService = adminUserPostService;
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.User_Index)]
        public async Task<IActionResult> IndexAsync(int did = 0, int page = 1, int limit = 15, int json = 0)
        {
            if (json == 1)
            {
                int gid = _LoginUtil.LoginGroupId();//判断普通用户不能看超级管理员
                Page<ViewAdminUser> list = await _adminUserService.GetPageListAsync(did, page, limit, gid);
                return Json(new { code = 0, data = list.Items, count = list.TotalItems });
            }
            ViewBag.deptid = did;
            return View();
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.User_Index)]
        public IActionResult UserTreeAsync()
        {
            return View();
        }
        [HttpGet]
        [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEdit)]
        public async Task<IActionResult> AddOrEditAsync(int id, int edit = 0)
        {
            if (edit == 1)
            {
                AdminUser user = await _adminUserService.GetNoCacheAsync(id);
                user.Password = null;
                return Json(new { status = 1, data = user });
            }
            int gid = _LoginUtil.LoginGroupId();

            List<AdminUserGroup> adminUserGroup = await _adminUserGroupService.GetListAsync();
            if (gid != 1)
                adminUserGroup.RemoveAll(e => e.Id == 1);//只有超级管理员才能添加超级管理员用户

            ViewBag.adminUserGroup = adminUserGroup;
            ViewBag.userDepts = await _adminUserDeptService.GetUserDeptListAsync();
            ViewBag.userPosts = await _adminUserPostService.GetAllAsync();
            ViewBag.id = id;
            return View();
        }
        [HttpGet]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.User_UserChange)]
        public async Task<IActionResult> UserChangeAsync(int json = 0)
        {
            int userId = await _LoginUtil.LoginUserId();
            if (json == 1)
            {
                ViewAdminUser user = await _adminUserService.GetAsync(userId);
                return Json(new { status = 1, data = user });
            }

            ViewBag.id = userId;
            return View();
        }

        [HttpPost]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.User_UserChange)]
        [Log(Name = "修改个人信息")]
        public async Task<IActionResult> UserChangePostAsync(EditAdminUser editAdminUser)
        {
            if (ModelState.IsValid)
            {
                int userId = await _LoginUtil.LoginUserId();

                if (1 > await _adminUserService.EditUserInfoUpdateAsync(editAdminUser, userId))
                    return Json(new { status = 0, msg = "修改失败，有可能是旧密码不正确！" });
                return Json(new { status = 1, msg = "修改个人信息:" + editAdminUser.Username + " - " + editAdminUser.Nickname });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }

        }

        [HttpPost, ActionName("CreatePost")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEdit)]
        [Log(Name = "新增用户")]
        public async Task<IActionResult> CreatePostAsync(EditAdminUser user)
        {
            if (ModelState.IsValid)
            {
                if (string.IsNullOrEmpty(user.Password))
                    return Json(new { status = 0, msg = "新增用户密码不能为空！" });

                if (await _adminUserService.GetByUsernameAsync(user.Username) == false)
                    return Json(new { status = 0, msg = "该登录名已存在，请重新输入！" });

                AdminUser adminUser = new()
                {
                    Gid = user.Gid,
                    DeptId = user.DeptId,
                    PostId = user.PostId,
                    Username = user.Username,
                    Password = MD5Utility.MD5Encrypt32(user.Password).ToLower(),
                    Nickname = user.Nickname,
                    Status = user.Status
                };
                var res = await _adminUserService.InsertAsync(adminUser);
                return Json(new { status = 1, msg = "添加成功 Id:" + res.ToString() });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }

        /// <summary>
        /// 修改
        /// </summary>
        [HttpPost, ActionName("EditPost")]
        [XssFieldFilter]//防Xss
        [ActionPermissionFilter(Permission = PermissionKeys.User_AddOrEdit)]
        [Log(Name = "修改用户")]
        public async Task<IActionResult> EditPost(EditAdminUser user, int id)
        {
            if (ModelState.IsValid)
            {
                AdminUser get = await _adminUserService.GetNoCacheAsync(id);
                if (get == null)
                    return Json(new { status = 0, msg = "请勿非法提交 Id:" + id });

                if (user.Username != get.Username && await _adminUserService.GetByUsernameAsync(user.Username) == false)
                    return Json(new { status = 0, msg = "该用户名已存在，请重新输入 Id:" + id });

                if (!string.IsNullOrEmpty(user.Password))
                    user.Password = MD5Utility.MD5Encrypt32(user.Password).ToLower();

                if (0 < await _adminUserService.UpdateAsync(user, id))
                    return Json(new { status = 1, msg = "编辑用户 Id:" + id });
                else
                    return Json(new { status = 0, msg = "编辑用户 Id:" + id });
            }
            else
            {
                var error = ModelState.GetErrorMessages();
                return Json(new { status = 0, msg = error });
            }
        }

        [HttpPost]
        [ActionPermissionFilter(Permission = PermissionKeys.User_Delete)]
        [Log(Name = "删除用户")]
        public async Task<IActionResult> Delete(int id)
        {
            if (await _adminUserService.DeleteByPriKeyAsync(id) > 0)
            {
                return Json(new { status = 1, msg = "删除用户 id:" + id });
            }
            else
                return Json(new { status = 0, msg = "删除失败！" });
        }

    }
}
